﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ChatForum.Business.Contract;
using System.Web.UI.WebControls;
using System.Web.Security;
using ChatForum.Business.Entity;

namespace ChatForum.Client
{
    internal class Handler
    {
        internal static void OnLogin(string userId, string password, bool createPersistentCookie = false)
        {
            try
            {
                ServiceHelper.ServiceHelper.AccountService.Login(userId, password);
                ChatForum.Business.Entity.User currentUser = ServiceHelper.ServiceHelper.AccountService.GetUser(userId);
                FormsAuthentication.SetAuthCookie(currentUser.UserId, createPersistentCookie);
				HttpContext.Current.Response.Redirect("~/Home.aspx", false);
            }
            catch (InvalidUserException ex)
            {
                HttpContext.Current.Session["PageError"] = ex.Message;
                FormsAuthentication.RedirectToLoginPage();
            }
            catch (InvalidPasswordException ex)
            {
                HttpContext.Current.Session["PageError"] = ex.Message;
                FormsAuthentication.RedirectToLoginPage();
			}
			catch (BlockedUserException ex)
			{
				HttpContext.Current.Session["PageError"] = ex.Message;
				FormsAuthentication.RedirectToLoginPage();
			}
            catch (ArgumentNullException ex)
            {
                HttpContext.Current.Session["PageError"] = ex.Message;
                FormsAuthentication.RedirectToLoginPage();
            }
            catch (Exception ex)
            {
                HttpContext.Current.Session["PageError"] = ex.Message;
                HttpContext.Current.Response.Redirect("~/Error.aspx", false);
            }
        }
        internal static void OnLogout(string userId)
        {
            try
            {
				ServiceHelper.ServiceHelper.AccountService.Logout(userId);
            }
            finally
            {
                FormsAuthentication.SignOut();
                FormsAuthentication.RedirectToLoginPage();
            }
        }

        internal static void OnRegister(Business.Entity.User user)
        {
            try
            {
                ServiceHelper.ServiceHelper.AccountService.RegisterUser(user);
                FormsAuthentication.RedirectToLoginPage();
            }
            catch (DuplicateUserIdException ex)
            {
                HttpContext.Current.Session["PageError"] = ex.Message;
            }
            catch (DuplicatePrimaryEmailException ex)
            {
                HttpContext.Current.Session["PageError"] = ex.Message;
            }
            catch (Exception e)
            {
                HttpContext.Current.Session["PageError"] = e.Message;
                HttpContext.Current.Response.Redirect("~/Error.aspx", false);
            }
        }

        internal static void ModifyAccount(Business.Entity.User user)
        {
            try
            {
                ServiceHelper.ServiceHelper.AccountService.ModifyAccountDetails(user);
                HttpContext.Current.Response.Redirect("~/Home.aspx", false);
            }
            catch (Exception ex)
            {
                HttpContext.Current.Session["PageError"] = ex.Message;
                HttpContext.Current.Response.Redirect("~/Error.aspx", false);
            }
        }

		internal static bool AddCategory(string name, string ageReq, string desc)
		{
			int outInt;
			if (string.IsNullOrWhiteSpace(name))
			{
				HttpContext.Current.Session["PageError"] = "Invalid Name";
				return false;
			}
			if (!Int32.TryParse(ageReq, out outInt))
			{
				HttpContext.Current.Session["PageError"] = "Invalid Age Requirement";
				return false;
			}
			if (string.IsNullOrWhiteSpace(desc))
			{
				HttpContext.Current.Session["PageError"] = "Invalid Description";
				return false;
			}
			bool success = false;
			ChatForum.Business.Entity.Category cat = new ChatForum.Business.Entity.Category()
			{
				Name = name,
				AgeRequirement = outInt,
				Description = desc,
				CreatedBy = HttpContext.Current.User.Identity.Name,
				ModifiedBy = HttpContext.Current.User.Identity.Name,
			};
			try
			{
				ServiceHelper.ServiceHelper.ForumService.CreateCategory(cat);
				success = true;
			}
			catch (DuplicateCategoryException ex)
			{
				HttpContext.Current.Session["PageError"] = ex.Message;
				success = false;
			}
			catch (Exception ex)
			{
				HttpContext.Current.Session["PageError"] = ex.Message;
				HttpContext.Current.Response.Redirect("~/Error.aspx", false);
				success = false;
			}
			return success;
		}
		internal static bool ModifyCategory(string title, string age, string desc)
		{
			int outInt;
			if (!Int32.TryParse(age, out outInt))
			{
				HttpContext.Current.Session["PageError"] = "Invalid Age Requirement";
				return false;
			}
			if (string.IsNullOrWhiteSpace(desc))
			{
				HttpContext.Current.Session["PageError"] = "Invalid Description";
				return false;
			}
			Category fromDb = ServiceHelper.ServiceHelper.ForumService.GetAllCategory().FirstOrDefault(c => c.Name == title);
			if (fromDb == null)
			{
				HttpContext.Current.Session["PageError"] = "Category not exist now. Please do a refresh.";
				return false;
			}
			fromDb.AgeRequirement = outInt;
			fromDb.Description = desc;
			bool success = false;
			try
			{
				ServiceHelper.ServiceHelper.ForumService.ModifyCategory(fromDb);
				success = true;
			}
			catch (Exception ex)
			{
				HttpContext.Current.Session["PageError"] = ex.Message;
				HttpContext.Current.Response.Redirect("~/Error.aspx", false);
				success = false;
			}
			return success;
		}
        internal static void AddPost(string desc, Guid parentCategoryId, Guid parentPostId)
        {
            Post post = new Post()
            {
                Description = desc,
                ParentCategory = parentCategoryId,
                ParentPost = parentPostId,
                Title = string.Empty,
                CreatedBy = HttpContext.Current.User.Identity.Name,
                ModifiedBy = HttpContext.Current.User.Identity.Name,
            };
            try
            {
                ServiceHelper.ServiceHelper.ForumService.CreatePost(post);
            }
            catch (InvalidCategoryException ex)
            {
                HttpContext.Current.Session["PageError"] = ex.Message;
            }
            catch (Exception ex)
            {
                HttpContext.Current.Session["PageError"] = ex.Message;
                HttpContext.Current.Response.Redirect("~/Error.aspx", false);
            }
        }
		internal static void AddPost(string desc, Guid parentCategoryId)
		{
            AddPost(desc, parentCategoryId, Guid.Empty);
		}
	}
}